# coding: utf-8

import json
import random
import time

from common.bid_notify.constant import IMContentType, ActionType
from common.bid_notify.utils import get_demand_info, JPush
from common.im_util import im_client
from common.models import model_factory, FeedbackStatus, Feedback, DemandStatus


class AppMessage(object):
    """
    create by ld_wu 2018-03-13
    """
    
    @classmethod
    def send_msg(cls, session, im_from, im_to, content, message_type, title, **kwargs):
        """
        发送App消息
        :return:
        """

        group_id = '%s:%s:%s' % tuple(
            sorted([str(im_from), str(im_to), str(message_type)[0]])
        )

        message = json.dumps(content, ensure_ascii=False)
        now = int(time.time())
        model_factory.im_messages.create(
            session,
            im_from=im_from,
            im_to=im_to,
            message_type=message_type,
            message=message,
            group_id=group_id,
            created_at=now * 1000,
            read_status=False
        )
        # iOS
        if 'ios_msg' in kwargs:
            im_client.single_sys_msg(
                im_from,
                im_to,
                kwargs['ios_msg'],
                title
            )

        # android
        if 'android_msg' in kwargs:
            kwargs['android_ext'].update(dict(
                msg_id='{}{}'.format(im_to, random.randint(1000, 9999))
            ))
            JPush().send_by_alias(
                kwargs['android_msg'],
                [im_to],
                title,
                ext=kwargs['android_ext']
            )
        
        
class AppContent(object):
    """
    create by ld_wu 2018-03-13
    
    """

    @classmethod
    def winner_content(cls, demand, mobile):
        demand_info = """位置在{city}\n{size}{surr}{color}显示，间距{span}\n电话：{mobile}"""
        msg = """您好，您已经竞拍成功了，请在10分钟内联系我，否则号码将失效。"""
        app_msg = dict(
            msg=msg,
            type=IMContentType.BID_SUCCESS,
            ext=json.dumps(
                dict(
                    demand_type=demand.cate_display,
                    demand_info=demand_info.format(
                        city=demand.city,
                        cate=demand.cate_display,
                        surr=demand.surr_display,
                        size=('\n' + str(demand.size) + '㎡') if demand.size else '',
                        color=demand.color_display,
                        span=(str(demand.span)) if demand.span else '',
                        mobile=mobile
                    ),
                    demand_status=demand.status,
                    demand_id=demand.id,
                    mobile=mobile
                )
            )
        )
        return app_msg

    @classmethod
    def recharge_content(cls, demand, pack, partic):
        msg = """您出价{offer}汇币竞拍的{city}{cate}订单已中标，由于您当前剩余{leave}汇币，无法完成支付，需立即充值以联系客户。"""
        app_msg = dict(
            msg=msg.format(
                city=demand.city,
                cate=demand.cate_display,
                offer=partic.offer,
                leave=pack.bid_point
            ),
            title='汇币不足通知',
            type=IMContentType.RECHARGE,
            ext=json.dumps(
                dict(
                    demand_type=demand.cate_display,
                    demand_id=demand.id,
                    for_sys=True,         # 客服系统消息
                    action_type=ActionType.ACCOUNT,
                    btn_name='速戳立即续费↓↓↓'
                )
            )
        )
        return app_msg

    @classmethod
    def follow_content(cls, demand, mobile, partic):
        demand_info = """位置在{city}\n{size}{surr}{color}显示，间距{span}\n电话：{mobile}"""
        msg = """您好，您已经抢单成功了，如需锁定订单或取消跟进，请尽快提交申请！"""
        app_msg = dict(
            msg=msg,
            type=IMContentType.FOLLOW,
            ext=json.dumps(
                dict(
                    demand_type=demand.cate_display,
                    demand_info=demand_info.format(
                        city=demand.city,
                        cate=demand.cate_display,
                        surr=demand.surr_display,
                        size=('\n' + str(demand.size) + '㎡') if demand.size else '',
                        color=demand.color_display,
                        span=(str(demand.span)) if demand.span else '',
                        mobile=mobile
                    ),
                    demand_id=demand.id,
                    mobile=mobile,
                    bid_win_at=partic.bid_win_at,
                    action_type=ActionType.DEMAND_DETAIL,
                )
            )
        )
        return app_msg

    @classmethod
    def gif_pack_content(cls):
        """
        create by ld_wu 2018-03-13
        赠送套餐内容
        :return:
        """

    @classmethod
    def approval_content(cls, demand, partic, add_point, minus_credit):
        """
        审核内容
        :return:
        """
        demand_info = """{city}{size}{span}{surr}{color}屏"""
        if partic.feedback_status == FeedbackStatus.PASS.value:
            msg = '您好, 您取消跟进的订单已审核通过。'
            res = '审核通过, 并退返{}汇币'.format(add_point)
            btn_name = '查看我的账户↓↓↓'
            action_type = ActionType.ACCOUNT
            title = '退单成功通知'
        else:
            msg = '您好, 您取消跟进的订单被驳回。'
            res = '驳回, 并扣除{}分成就值'.format(minus_credit)
            btn_name = '查看订单详情↓↓↓'
            action_type = ActionType.DEMAND_DETAIL
            title = '退单驳回通知'
        app_msg = dict(
            msg=msg,
            type=IMContentType.APPROVAL,
            title=title,
            ext=json.dumps(
                dict(
                    demand_id=demand.id,
                    remark='不合理的退单会影响抢单哦!',
                    feedback=Feedback(partic.feedback).display,
                    demand_info=demand_info.format(
                        city=demand.city,
                        surr=demand.surr_display,
                        size=(str(demand.size) + '平米') if demand.size else '',
                        color=demand.color_display,
                        span=(str(demand.span)) if demand.span else '',
                    ),
                    demand_status=demand.status,
                    feedback_refuse_content=partic.feedback_refuse_content,
                    operate_res=res,
                    for_sys=True,    # 客服系统消息
                    btn_name=btn_name,
                    action_type=action_type
                )
            )
        )
        return app_msg

    @classmethod
    def level_up_content(cls):
        """
        create_by ld_wu 2018-03-13
        等级提升内容
        """

    @classmethod
    def new_order_content(cls, demand, msg_type=0):
        """
        create by ld_wu 2018-03-13
        新订单消息内容
        :return:
        """
        if not demand:
            return ''

        demand_info = get_demand_info(demand)
        return dict(
            msg='{cate}订单，位置：{address} {demand_info}'.format(
                cate=demand.cate_display,
                address=demand.city,
                demand_info=demand_info
            ),
            type=msg_type,
            ext=json.dumps(
                dict(demand_id=demand.id)
            )
        )

    @classmethod
    def winner_notify_content(cls, demand, mobile):
        demand_info = """位置在{city}\n{size}{surr}{color}显示，间距{span}\n电话：{mobile}"""
        msg = """订单还剩5分钟超时, 尽快联系我！超时号码将失效。"""
        app_msg = dict(
            msg=msg,
            type=IMContentType.BID_SUCCESS,
            ext=json.dumps(
                dict(
                    demand_type=demand.cate_display,
                    demand_info=demand_info.format(
                        city=demand.city,
                        cate=demand.cate_display,
                        surr=demand.surr_display,
                        size=('\n' + str(demand.size) + '㎡') if demand.size else '',
                        color=demand.color_display,
                        span=(str(demand.span)) if demand.span else '',
                        mobile=mobile
                    ),
                    demand_status=demand.status,
                    demand_id=demand.id,
                    mobile=mobile
                )
            )
        )
        return app_msg

    @classmethod
    def timeout_payback_content(cls, demand, ret_bid_point):
        msg = """订单超时未联系, 系统自动退还{offer}(70%)汇币。"""
        demand_info = """{city}{size}平米{span}{surr}{color}屏"""
        app_msg = dict(
            msg=msg.format(
                offer=ret_bid_point
            ),
            title='退款通知',
            type=IMContentType.TIMEOUT_PAYBACK,
            ext=json.dumps(
                dict(
                    demand_type=demand.cate_display,
                    demand_info=demand_info.format(
                        city=demand.city,
                        surr=demand.surr_display,
                        size=str(demand.size),
                        color=demand.color_display,
                        span=(str(demand.span)) if demand.span else '',
                    ),
                    ret_bid_point=ret_bid_point,
                    demand_id=demand.id,
                    for_sys=True,  # 客服系统消息
                    action_type=ActionType.DEMAND_DETAIL,
                    btn_name='及时联系客户, 珍惜销售机会！↓↓↓'
                )
            )
        )
        return app_msg

    @classmethod
    def app_invite_new_user_content(cls, invite_user, user, invite_datetime):
        """
        created by chenhj at 2018/6/28
        @:param invite_user: 邀请人
        @:param user: 下线
        @:param invite_datetime: 邀请时间
        """
        msg = """您的运营中心又增加新成员了, 快去拓展人脉看看吧！"""
        app_msg = dict(
            msg=msg,
            title='新增成员通知',
            type=IMContentType.INVITE_NEW_USER,
            ext=json.dumps(
                dict(
                    new_username=user.nickname,
                    invite_username=invite_user.nickname,
                    invite_datetime=invite_datetime.strftime('%F %T'),
                    for_sys=True,  # 客服系统消息
                    action_type=ActionType.RELATION_PAGE,
                )
            )
        )
        return app_msg

    @classmethod
    def lock_return_dispatch_content(cls, demand, message_type):
        title = '退款通知'
        msg = '{}、{}㎡、{}、{}、{}屏被其他用户锁定, 系统自动退返1个派单点'.format(
            demand.city, demand.size, demand.span,
            demand.surr_display, demand.color_display
        )
        app_msg = dict(
            msg=msg,
            title=title,
            type=message_type,
            ext=json.dumps(
                dict(
                    ret_dispatch_info='1个派单点',
                    reason='派送订单被其他用户锁定',
                    demand_id=demand.id,
                    demand_status=DemandStatus.DISPATCHING.value,
                    for_sys=True,  # 客服系统消息
                    action_type=ActionType.DEMAND_DETAIL,
                    btn_name='查看订单↓↓↓'
                )
            )
        )
        return app_msg

